﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace JXT.PrimaryKey.Batman.Core.Extensions
{
    /// <summary>
    /// 系统基本项扩展
    /// </summary>
    public static class SystemEnvironment
    {
        private const string PATH_NAME = "PATH";

        /// <summary>
        /// 当前所在目录
        /// </summary>
        public static string ApplicationBase
        {
            get { return AppDomain.CurrentDomain.SetupInformation.ApplicationBase; }
        }

        /// <summary>
        /// 当前程序集名称
        /// </summary>
        public static string ApplicationName
        {
            get { return AppDomain.CurrentDomain.SetupInformation.ApplicationName; }
        }

        /// <summary>
        /// 当前程序集完整路径
        /// </summary>
        public static string ApplicationPath
        {
            get { return Path.Combine(ApplicationBase, ApplicationName); }
        }

        /// <summary>
        /// 将当前程序集路径加入PATH环境变量
        /// </summary>
        public static void AddCurrentApplicationPath()
        {
            string path = Environment.GetEnvironmentVariable(PATH_NAME);
            if (path == null)
            {
                Environment.SetEnvironmentVariable(PATH_NAME, ApplicationBase);
            }
            else
            {
                Environment.SetEnvironmentVariable(PATH_NAME, String.Format("{0}{1}{2}", path, Path.PathSeparator, ApplicationBase));
            }
        }

        /// <summary>
        /// 获取正在允许的进程对象
        /// </summary>
        /// <returns></returns>
        public static Process GetRunningInstance()
        {
            Process currentProcess = Process.GetCurrentProcess();
            string currentFileName = currentProcess.MainModule.FileName;
            Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
            foreach (Process process in processes)
            {
                if (process.MainModule.FileName == currentFileName)
                {
                    if (process.Id != currentProcess.Id)
                        return process;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取正在运行的进程实例
        /// </summary>
        /// <param name="processFileName">进程名称</param>
        /// <returns></returns>
        public static Process[] GetRunningInstances(string processFileName)
        {
            Process[] processes = Process.GetProcesses();
            IList<Process> result = new List<Process>();
            foreach (var item in processes)
            {
                try
                {
                    if (item.MainModule.ModuleName == processFileName)
                        result.Add(item);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(String.Format("scan process error for {0}.", e.Message));
                }
            }
            return result.ToArray();
        }

        /// <summary>
        /// 处理进程对象
        /// </summary>
        /// <param name="instance">进行对象</param>
        public static void HandleRunningInstance(Process instance)
        {
            ShowWindowAsync(instance.MainWindowHandle, WS_SHOWNORMAL);
            SetForegroundWindow(instance.MainWindowHandle);
        }

        /// <summary>
        /// 判断当前进程是否以管理员运行
        /// </summary>
        /// <returns></returns>
        public static bool IsAdmin()
        {
            return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
        }

        private const int WS_SHOWNORMAL = 1;

        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        /// <summary>
        /// 启动控制台
        /// </summary>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        public static extern bool AllocConsole();
        /// <summary>
        /// 释放控制台
        /// </summary>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        public static extern bool FreeConsole();  

        [DllImport("user32")]
        public static extern UInt32 SendMessage(IntPtr hWnd, UInt32 msg, UInt32 wParam, UInt32 lParam);

    }
}
